import { amapInitCompuleted } from "@/bus";
import * as markerApi from "@/api/markerApi";
import { ResponseCode } from "@/common/Responsetypes";
import type { Ref } from "vue";
import type { IPoiExt } from "@/common/MapTypes";
import type { AMapCustomExposed } from "@/components/amapCustom/types";
import { isArray } from "lodash-es";
import { useMarkerStore } from "@/stores/useMarkerStore";
import { useUserStore } from "@/stores/useUserStore";
import { storeToRefs } from "pinia";
import type { IPopupFlexExposed } from "@/components/popupFlex/types";

export default function (
  amapRef: Ref<AMapCustomExposed | null>,
  popupFlexRef: Ref<IPopupFlexExposed | null>
) {
  const { setActiveMarker, setMarkers } = useMarkerStore();
  const userStore = useUserStore();
  const { userInfo } = storeToRefs(userStore);

  uni.$on(amapInitCompuleted, () => {
    if (userInfo.value) {
      markerApi.findById().then((result) => {
        if (result.code === ResponseCode.PASS && isArray(result.data)) {
          result.data.forEach((item: IPoiExt) => {
            amapRef.value?.addMarkerToMap(item, {
              onClick(event) {
                setActiveMarker(event);
                // 关闭 搜索的 Popup
                popupFlexRef.value?.close();
              },
            });
          });
        }
        setMarkers(result.data as IPoiExt[]);
        amapRef.value?.setFitView();
      });
    }
  });

  return {};
}
